export let name = "productList";

export function render() {
    return `
     <style>
         

         .container {
             max-width: 1200px;
             margin: 0 auto;
             background-color: #fff;
             border-radius: 8px;
             box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
             padding: 20px;
         }

         .header {
             display: flex;
             justify-content: space-between;
             align-items: center;
             margin-bottom: 20px;
             padding-bottom: 20px;
             border-bottom: 1px solid #eee;
         }

         .title {
             font-size: 24px;
             color: #333;
         }

         .toolbar {
             display: flex;
             gap: 10px;
         }

         .search-box {
             position: relative;
         }

         .search-box input {
             padding: 8px 35px 8px 15px;
             border: 1px solid #ddd;
             border-radius: 4px;
             width: 250px;
         }

         .search-box::after {
             content: "🔍";
             position: absolute;
             right: 10px;
             top: 50%;
             transform: translateY(-50%);
         }

         .btn {
             padding: 8px 16px;
             border: none;
             border-radius: 4px;
             cursor: pointer;
             transition: background-color 0.3s;
         }

         .btn-primary {
             background-color: #7438d5;
             color: white;
            
         }

         .btn-primary:hover {
             background-color: #5d2bb0;
         }

         .btn-success {
             background-color: #1b44e3;
             color: white;
         }

         .btn-success:hover {
             background-color: #1fd0c2;
         }

         table {
             width: 100%;
             border-collapse: collapse;
             margin-bottom: 20px;
         }

         th, td {
             padding: 12px 15px;
             text-align: left;
             border-bottom: 1px solid #ddd;
         }

         th {
             background-color: #f2f2f2;
             font-weight: bold;
         }

         tr:hover {
             background-color: #f5f5f5;
         }

         .badge {
             padding: 4px 8px;
             border-radius: 4px;
             font-size: 12px;
             font-weight: bold;
         }

         .badge-success {
             background-color: #dff0d8;
             color: #3c763d;
         }

         .badge-danger {
             background-color: #f2dede;
             color: #a94442;
         }

         .action-btn {
             padding: 6px 12px;
             margin-right: 5px;
             border: none;
             border-radius: 4px;
             cursor: pointer;
             transition: background-color 0.3s;
         }

         .action-btn.edit {
             background-color: #000000;
             color: #ffffff;
         }

         .action-btn.edit:hover {
             background-color: #969292;
         }

         .action-btn.delete {
             background-color: #1a1919;
             color: #ffffff;
         }

         .action-btn.delete:hover {
             background-color: #969292;
         }

         .pagination {
             display: flex;
             justify-content: center;
             align-items: center;
             gap: 5px;
         }

         .pagination-btn {
             padding: 8px 12px;
             border: 1px solid #ddd;
             background-color: white;
             cursor: pointer;
             border-radius: 4px;
         }

         .pagination-btn.active {
             background-color: #7438d5;
             color: white;
             border-color: #7438d5;
         }

         .pagination-btn:disabled {
             opacity: 0.5;
             cursor: not-allowed;
         }

         .modal {
             display: none;
             position: fixed;
             z-index: 1000;
             left: 0;
             top: 0;
             width: 100%;
             height: 100%;
             background-color: rgba(0,0,0,0.4);
         }

         .modal-content {
             background-color: #fefefe;
             margin: 10% auto;
             padding: 20px;
             border: 1px solid #888;
             width: 50%;
             max-width: 600px;
             border-radius: 8px;
             box-shadow: 0 4px 8px rgba(0,0,0,0.1);
         }

         .modal-header {
             display: flex;
             justify-content: space-between;
             align-items: center;
             margin-bottom: 20px;
             padding-bottom: 10px;
             border-bottom: 1px solid #eee;
         }

         .modal-title {
             font-size: 20px;
             font-weight: bold;
         }

         .close {
             color: #aaa;
             font-size: 28px;
             font-weight: bold;
             cursor: pointer;
         }

         .close:hover {
             color: black;
         }

         .form-group {
             margin-bottom: 15px;
         }

         .form-group label {
             display: block;
             margin-bottom: 5px;
             font-weight: bold;
         }

         .form-control {
             width: 100%;
             padding: 10px;
             border: 1px solid #ddd;
             border-radius: 4px;
             box-sizing: border-box;
         }

         .form-actions {
             display: flex;
             justify-content: flex-end;
             gap: 10px;
             margin-top: 20px;
         }

         .alert {
             padding: 15px;
             margin-bottom: 20px;
             border-radius: 4px;
         }

         .alert-success {
             background-color: #dff0d8;
             color: #3c763d;
         }

         .no-data {
             text-align: center;
             padding: 20px;
             color: #777;
         }
         .container {
           max-width: 1200px;
           margin: 0 auto;
           background-color: #fff;
           border-radius: 8px;
           box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
           padding: 20px;
           /* 新增：限制容器最大高度，超出则显示滚动条 */
           max-height: 80vh; /* 80%视口高度 */
           overflow: hidden; /* 隐藏容器内部溢出内容 */
         }
         
         #productTableContainer {
             /* 新增：表格容器设置滚动 */
             max-height: calc(80vh - 180px); /* 减去头部和分页的高度 */
             overflow-y: auto; /* 垂直方向超出时显示滚动条 */
             margin-bottom: 20px; /* 与分页保持距离 */
         }
         
         /* 优化滚动条样式（可选） */
         #productTableContainer::-webkit-scrollbar {
             width: 8px; /* 滚动条宽度 */
         }
         
         #productTableContainer::-webkit-scrollbar-track {
             background: #f1f1f1; /* 滚动条轨道背景 */
             border-radius: 4px;
         }
         
         #productTableContainer::-webkit-scrollbar-thumb {
             background: #bbb; /* 滚动条滑块颜色 */
             border-radius: 4px;
         }
         
         #productTableContainer::-webkit-scrollbar-thumb:hover {
             background: #999; /* 滚动条滑块hover颜色 */
         }
     </style>

     <div class="container">
        <div class="header">
            <h1 class="title">产品列表</h1>
            <div class="toolbar">
                <div class="search-box">
                    <input type="text" id="searchInput" placeholder="搜索产品...">
                </div>
                <button class="btn btn-success" id="addProductBtn">添加产品</button>
            </div>
        </div>

        <div id="productTableContainer">
            <table id="productTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>产品名称</th>
                        <th>类别</th>
                        <th>价格</th>
                        <th>库存状态</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="productTableBody">
                    <!-- 产品数据将通过JavaScript动态生成 -->
                </tbody>
            </table>
            <div id="noDataMessage" class="no-data" style="display: none;">没有找到产品数据</div>
        </div>

        <div class="pagination" id="pagination">
            <!-- 分页按钮将通过JavaScript动态生成 -->
        </div>
     </div>

     <!-- 添加/编辑产品的模态框 -->
     <div id="productModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="modalTitle">添加产品</h2>
                <span class="close">&times;</span>
            </div>
            <form id="productForm">
                <input type="hidden" id="productId">
                <div class="form-group">
                    <label for="productName">产品名称</label>
                    <input type="text" class="form-control" id="productName" required>
                </div>
                <div class="form-group">
                    <label for="productCategory">产品类别</label>
                    <select class="form-control" id="productCategory" required>
                        <option value="">请选择类别</option>
                        <option value="电子产品">电子产品</option>
                        <option value="家居用品">家居用品</option>
                        <option value="服装">服装</option>
                        <option value="食品">食品</option>
                        <option value="图书">图书</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="productPrice">价格</label>
                    <input type="number" class="form-control" id="productPrice" min="0" step="0.01" required>
                </div>
                <div class="form-group">
                    <label for="productStock">库存状态</label>
                    <select class="form-control" id="productStock" required>
                        <option value="in-stock">有货</option>
                        <option value="out-of-stock">缺货</option>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn" id="cancelBtn">取消</button>
                    <button type="submit" class="btn btn-primary" id="saveBtn">保存</button>
                </div>
            </form>
        </div>
     </div>

     <!-- 通知提示 -->
     <div id="notification" class="alert alert-success" style="display: none; position: fixed; top: 20px; right: 20px; z-index: 1050;"></div>
    `;
}

export function afterRender() {
    // 本地存储键名
    var STORAGE_KEY = 'productListData';

    // 获取DOM元素
    var productTableBody = document.getElementById('productTableBody');
    var noDataMessage = document.getElementById('noDataMessage');
    var searchInput = document.getElementById('searchInput');
    var addProductBtn = document.getElementById('addProductBtn');
    var modal = document.getElementById('productModal');
    var modalTitle = document.getElementById('modalTitle');
    var productForm = document.getElementById('productForm');
    var productIdInput = document.getElementById('productId');
    var productNameInput = document.getElementById('productName');
    var productCategoryInput = document.getElementById('productCategory');
    var productPriceInput = document.getElementById('productPrice');
    var productStockInput = document.getElementById('productStock');
    var cancelBtn = document.getElementById('cancelBtn');
    var closeBtn = document.querySelector('.close');
    var notification = document.getElementById('notification');
    var pagination = document.getElementById('pagination');

    // 分页相关变量
    let currentPage = 1;
    const itemsPerPage = 5;
    let filteredProducts = [];

    // 初始化
    init();

    // 初始化函数
    function init() {
        // 从本地存储加载数据
        loadProducts();

        // 渲染产品表格
        renderProductTable();

        // 设置事件监听器
        setupEventListeners();
    }

    // 从本地存储加载产品数据，并按ID升序排序
    function loadProducts() {
        var storedData = localStorage.getItem(STORAGE_KEY);
        if (storedData) {
            filteredProducts = JSON.parse(storedData);
        } else {
            // 默认示例数据
            filteredProducts = [
                {
                    id: 1,
                    name: "iPhone 13",
                    category: "电子产品",
                    price: 5999,
                    stock: "in-stock",
                    createdAt: new Date().toISOString()
                },
                {
                    id: 2,
                    name: "小米电视5",
                    category: "电子产品",
                    price: 3299,
                    stock: "in-stock",
                    createdAt: new Date().toISOString()
                },
                {
                    id: 3,
                    name: "华为MateBook 14",
                    category: "电子产品",
                    price: 5699,
                    stock: "out-of-stock",
                    createdAt: new Date().toISOString()
                },
                {
                    id: 4,
                    name: "欧式沙发",
                    category: "家居用品",
                    price: 2599,
                    stock: "in-stock",
                    createdAt: new Date().toISOString()
                },
                {
                    id: 5,
                    name: "纯棉四件套",
                    category: "家居用品",
                    price: 399,
                    stock: "in-stock",
                    createdAt: new Date().toISOString()
                }
            ];
            saveProducts();
        }

        // 按ID升序排序
        filteredProducts.sort((a, b) => a.id - b.id);
    }

    // 保存产品数据到本地存储
    function saveProducts() {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(filteredProducts));
    }

    // 渲染产品表格
    function renderProductTable() {
        // 清空表格
        productTableBody.innerHTML = '';

        // 获取当前页数据
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = Math.min(startIndex + itemsPerPage, filteredProducts.length);
        const currentProducts = filteredProducts.slice(startIndex, endIndex);

        // 如果没有数据，显示提示信息
        if (currentProducts.length === 0) {
            noDataMessage.style.display = 'block';
            productTableBody.style.display = 'none';
        } else {
            noDataMessage.style.display = 'none';
            productTableBody.style.display = 'table-row-group';

            // 渲染产品行
            currentProducts.forEach(product => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${product.id}</td>
                    <td>${product.name}</td>
                    <td>${product.category}</td>
                    <td>¥${product.price.toFixed(2)}</td>
                    <td><span class="badge ${product.stock === 'in-stock' ? 'badge-success' : 'badge-danger'}">${
                    product.stock === 'in-stock' ? '有货' : '缺货'
                }</span></td>
                    <td>${new Date(product.createdAt).toLocaleString()}</td>
                    <td>
                        <button class="action-btn edit" data-id="${product.id}">编辑</button>
                        <button class="action-btn delete" data-id="${product.id}">删除</button>
                    </td>
                `;
                productTableBody.appendChild(row);
            });
        }

        // 渲染分页
        renderPagination();
    }

    // 渲染分页
    function renderPagination() {
        pagination.innerHTML = '';

        const totalPages = Math.ceil(filteredProducts.length / itemsPerPage);

        if (totalPages <= 1) return;

        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.className = 'pagination-btn';
        prevBtn.textContent = '上一页';
        prevBtn.disabled = currentPage === 1;
        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                renderProductTable();
            }
        });
        pagination.appendChild(prevBtn);

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = 'pagination-btn';
            pageBtn.textContent = i;
            if (i === currentPage) {
                pageBtn.classList.add('active');
            }
            pageBtn.addEventListener('click', () => {
                currentPage = i;
                renderProductTable();
            });
            pagination.appendChild(pageBtn);
        }

        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.className = 'pagination-btn';
        nextBtn.textContent = '下一页';
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                currentPage++;
                renderProductTable();
            }
        });
        pagination.appendChild(nextBtn);
    }

    // 设置事件监听器
    function setupEventListeners() {
        // 搜索功能
        searchInput.addEventListener('input', handleSearch);

        // 添加产品按钮
        addProductBtn.addEventListener('click', openAddModal);

        // 编辑和删除按钮（委托事件）
        productTableBody.addEventListener('click', function(e) {
            if (e.target.classList.contains('edit')) {
                const productId = parseInt(e.target.getAttribute('data-id'));
                openEditModal(productId);
            }

            if (e.target.classList.contains('delete')) {
                const productId = parseInt(e.target.getAttribute('data-id'));
                deleteProduct(productId);
            }
        });

        // 模态框关闭按钮
        closeBtn.addEventListener('click', closeModal);
        cancelBtn.addEventListener('click', closeModal);

        // 点击模态框外部关闭
        window.addEventListener('click', function(e) {
            if (e.target === modal) {
                closeModal();
            }
        });

        // 表单提交
        productForm.addEventListener('submit', function(e) {
            e.preventDefault();
            saveProduct();
        });
    }

    // 处理搜索
    function handleSearch() {
        const keyword = searchInput.value.trim().toLowerCase();

        // 先从本地存储重新加载所有数据
        const allProducts = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');

        if (keyword) {
            filteredProducts = allProducts.filter(product =>
                product.id.toString().includes(keyword) ||
                product.name.toLowerCase().includes(keyword) ||
                product.category.toLowerCase().includes(keyword)
            );
        } else {
            // 重置为所有产品
            filteredProducts = [...allProducts];
        }

        // 搜索后仍然保持ID升序
        filteredProducts.sort((a, b) => a.id - b.id);

        currentPage = 1;
        renderProductTable();
    }

    // 打开添加模态框
    function openAddModal() {
        modalTitle.textContent = '添加产品';
        productForm.reset();
        productIdInput.value = '';
        modal.style.display = 'block';
    }

    // 打开编辑模态框
    function openEditModal(productId) {
        const product = filteredProducts.find(p => p.id === productId);
        if (product) {
            modalTitle.textContent = '编辑产品';
            productIdInput.value = product.id;
            productNameInput.value = product.name;
            productCategoryInput.value = product.category;
            productPriceInput.value = product.price;
            productStockInput.value = product.stock;
            modal.style.display = 'block';
        }
    }

    // 关闭模态框
    function closeModal() {
        modal.style.display = 'none';
    }

    // 保存产品
    function saveProduct() {
        const productData = {
            id: productIdInput.value ? parseInt(productIdInput.value) : generateNewId(),
            name: productNameInput.value,
            category: productCategoryInput.value,
            price: parseFloat(productPriceInput.value),
            stock: productStockInput.value,
            createdAt: productIdInput.value ?
                filteredProducts.find(p => p.id === parseInt(productIdInput.value)).createdAt :
                new Date().toISOString()
        };

        if (productIdInput.value) {
            // 更新现有产品
            const index = filteredProducts.findIndex(p => p.id === productData.id);
            if (index !== -1) {
                filteredProducts[index] = productData;
                showNotification('产品更新成功');
            }
        } else {
            // 添加新产品
            filteredProducts.push(productData);
            showNotification('产品添加成功');
        }

        // 保存前按ID升序排序
        filteredProducts.sort((a, b) => a.id - b.id);

        // 保存到本地存储
        saveProducts();

        // 重新渲染
        currentPage = 1;
        renderProductTable();
        closeModal();
    }

    // 生成新ID
    function generateNewId() {
        return filteredProducts.length > 0 ? Math.max(...filteredProducts.map(p => p.id)) + 1 : 1;
    }

    // 删除产品
    function deleteProduct(productId) {
        if (confirm('确定要删除这个产品吗？')) {
            filteredProducts = filteredProducts.filter(p => p.id !== productId);
            // 删除后保持排序
            filteredProducts.sort((a, b) => a.id - b.id);
            saveProducts();
            renderProductTable();
            showNotification('产品删除成功');
        }
    }

    // 显示通知
    function showNotification(message) {
        notification.textContent = message;
        notification.style.display = 'block';

        setTimeout(() => {
            notification.style.display = 'none';
        }, 3000);
    }
}
